/*
 * This file is part of "IdeWiki" project.
 *
 * Copyright (c) 2008 Hendrik Ebel
 * All Rights Reserved.
 *
 * Please visit http://code.google.com/p/idewiki for updates and contact.
 *
 * --LICENSE NOTICE--
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 3
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; If not, see <http://www.gnu.org/licenses/>.
 * --LICENSE NOTICE--
 */
package ws.ebel.idewiki;

import java.net.MalformedURLException;
import java.net.URL;

import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabFolder2Listener;
import org.eclipse.swt.custom.CTabFolderEvent;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.part.ViewPart;

import ws.ebel.idewiki.browser.IdeWikiBrowser;
import ws.ebel.idewiki.editors.IdeWikiEditor;
import ws.ebel.idewiki.xmlrpc.SnipBean;

/**
 * The Class IdeWikiBrowserEditor.
 */
public class IdeWikiBrowserEditor extends ViewPart implements IResourceChangeListener, IPropertyChangeListener {

    /** The wiki browser. */
    private IdeWikiBrowser wikiBrowser;
    
    /** The help action. */
    private Action helpAction;
	
	/** The about action. */
	private Action aboutAction;

    /**
     * The Constructor.
     */
    public IdeWikiBrowserEditor() {
        super();
        ResourcesPlugin.getWorkspace().addResourceChangeListener(this);

    }

    /**
     * Creates the part control.
     * 
     * @param parent the parent
     */
    @Override
    public void createPartControl(Composite parent) {
        createContents(parent);
    }

    /**
     * Creates the contents.
     * 
     * @param parent the parent composite
     */
    private void createContents(Composite parent) {
        // Create the containing tab folder
        final CTabFolder tabFolder = new CTabFolder(parent, SWT.BOTTOM);
        wikiBrowser = new IdeWikiBrowser(tabFolder, getViewSite());

        // Create each tab and set its text, tool tip text,
        // image, and control
        CTabItem one = new CTabItem(tabFolder, SWT.NONE);
        one.setText("Browser");
        one.setImage(createImage("icons/browser.gif"));
        one.setToolTipText("This is tab one");
        one.setControl(wikiBrowser.getDisplayArea());
        one.setData(wikiBrowser);
        // Select the first tab (index is zero-based)
        tabFolder.setSelection(0);

        tabFolder.addCTabFolder2Listener(new CTabFolder2Listener() {

            public void close(CTabFolderEvent event) {
                if (event.item instanceof CTabItem) {
                    CTabItem item = (CTabItem) event.item;
                    IdeWikiEditor currentEditor = (IdeWikiEditor) item.getData();
                    
                    if (currentEditor.isChangeFlag()) {
                        MessageBox messageBox = new MessageBox(tabFolder.getShell(), SWT.ICON_WARNING | SWT.YES | SWT.NO
                                | SWT.CANCEL);
                        messageBox.setText("Warning");
                        messageBox.setMessage("Save the changes before exiting?");
                        int buttonID = messageBox.open();
                        switch (buttonID) {
                        case SWT.YES:
                            Button saveButton = currentEditor.getSaveButton();
                            currentEditor.saveAction((SnipBean) saveButton.getData());
                            break;
                        case SWT.NO:
                            Button abortButton = currentEditor.getAbortButton();
                            currentEditor.closeAction((CTabItem) abortButton.getData());
                            break;
                       default:
                            // does nothing ...
                            event.doit = false;
                        }
                    } else {
                        currentEditor.closeAction(item);
                    }
                }
            }

            public void maximize(CTabFolderEvent event) {
                // to nothing
            }

            public void minimize(CTabFolderEvent event) {
                // to nothing
            }

            public void restore(CTabFolderEvent event) {
                // to nothing
            }

            public void showList(CTabFolderEvent event) {
                // to nothing
            }

        });
        
        fillLocalPullDown();
        

        // Add an event listener to write the selected tab to stdout
        //        tabFolder.addSelectionListener(new SelectionAdapter() {
        //            public void widgetSelected(org.eclipse.swt.events.SelectionEvent event) {
        //            }
        //        });
    }
    
    
    /**
     * Fill local pull down.
     */
    private void fillLocalPullDown() {
    	IActionBars bars = getViewSite().getActionBars();
		IMenuManager manager = bars.getMenuManager();
    	
		aboutAction = new Action() {
			public void run() {
				MessageDialog.openInformation(
						wikiBrowser.getDisplayArea().getShell(),
						"About IDE Wiki",
						"IDE Wiki by Hendrik Ebel" +
						"\nlicensed under GNU General Public License v3.0");
			}
		};
		aboutAction.setText("About IDE Wiki");
		aboutAction.setToolTipText("About IDE Wiki");
		
		helpAction = new Action() {
			public void run() {
				wikiBrowser.openLocation("http://code.google.com/p/ide-wiki/");
			}
		};
		helpAction.setText("Help");
		helpAction.setToolTipText("Help");
		helpAction.setImageDescriptor(getImageDescriptor("icons/help.gif"));
		
		manager.add(aboutAction);
		manager.add(new Separator());
		manager.add(helpAction);
	}

    /**
     * Dispose.
     */
    public void dispose() {
        Activator.getDefault().getPreferenceStore().removePropertyChangeListener(this);
        ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
        wikiBrowser.dispose();
        super.dispose();
    }

    /**
     * Sets the focus.
     */
    @Override
    public void setFocus() {
        // Auto-generated method stub

    }

    /**
     * Resource changed.
     * 
     * @param event the event
     * 
     * @see org.eclipse.core.resources.IResourceChangeListener#resourceChanged(org.eclipse.core.resources.IResourceChangeEvent)
     */
    public void resourceChanged(IResourceChangeEvent event) {
        // Auto-generated method stub

    }

    /**
     * Property change.
     * 
     * @param event the event
     * 
     * @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent)
     */
    public void propertyChange(PropertyChangeEvent event) {
        // Auto-generated method stub

    }

    /**
     * Creates the image.
     * 
     * @param path the path
     * 
     * @return the image
     */
    private Image createImage(String path) {
        ImageDescriptor imageDesc = getImageDescriptor(path);
        Image result = imageDesc.createImage();
        return result;
    }

    /**
     * Creates the image.
     * 
     * @param path the path
     * 
     * @return the image
     */
    private ImageDescriptor getImageDescriptor(String path) {
        URL installURL = Activator.getDefault().getBundle().getEntry("/");
        ImageDescriptor imageDesc = null;
        try {
            imageDesc = ImageDescriptor.createFromURL(new URL(installURL, path));
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        }
        return imageDesc;
    }
}
